package com.gsdse.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gsdse.dao.ApplyDao;
import com.gsdse.dao.UserDao;
import com.gsdse.pojo.ApplyTime;
import com.gsdse.pojo.ReturnData;
import com.gsdse.pojo.User;
import com.gsdse.pojo.apply;
import com.gsdse.service.ApplyService;
import com.gsdse.service.SendEmailService;
import com.gsdse.utils.EmailConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
@Service
public class ApplyServiceImpl implements ApplyService, DisposableBean {

    @Autowired
    private ApplyDao applyDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SendEmailService sendEmailService;
    private static final ExecutorService HANDLEQUEUE_EXECUTOR= Executors.newSingleThreadExecutor();

    //阻塞队列
    public static BlockingQueue<Map.Entry<String,Object>> applyQueue=new LinkedBlockingQueue(1024);

    @PostConstruct
    private void init(){
        HANDLEQUEUE_EXECUTOR.submit(new handleApplyQueue());
        log.info("线程启动！");
    }

    @Override
    public void destroy() throws Exception {
        HANDLEQUEUE_EXECUTOR.shutdownNow();
        log.info("线程销毁 ！");
    }

    public class handleApplyQueue implements Runnable{
        @Override
        public void run() {
            while(true){
                try {
                    Map.Entry<String, Object> take = applyQueue.take();
                    //发送录取结果邮件
                    if("1".equals(take.getKey()))
                    {
                        apply apply = applyDao.selectApplyByApplyId(Integer.parseInt(take.getValue().toString()));
                        String email = userDao.selectEmailByUserId(apply.getUserId());

                        if (StringUtils.isEmpty(email)||"".equals(email)){
                            continue;
                        }
                        if (("1".equals(apply.getFirstStatus()) || "0".equals(apply.getFirstStatus())) && ("1".equals(apply.getSecondStatus()) || "0".equals(apply.getSecondStatus()))) {
                            sendEmailService.sendWxchangeDutyEmail(email, "您的投递结果已出炉，请到广师科教小程序查询结果！", "录取结果通知");

                        }


                        log.info("发送查询通知");
                    }//发送面试群二维码
                    else if("2".equals(take.getKey()))
                    {
                        apply apply = applyDao.selectApplyByApplyId(Integer.parseInt(take.getValue().toString()));
                        String email = userDao.selectEmailByUserId(apply.getUserId());

                        if (StringUtils.isEmpty(email)||"".equals(email)){
                            continue;
                        }
                        if(!("0".equals(apply.getFirstWilling()))){
                            sendEmailService.sendPicEmail(email,"面试通知","投递成功，请及时加入对应面试群哦！",apply.getFirstWilling());
                        }

                        if(!("0".equals(apply.getSecondWilling()))){
                            sendEmailService.sendPicEmail(email,"面试通知","投递成功，请及时加入对应面试群哦！",apply.getSecondWilling());
                        }
                        log.info("发送面试群邮箱");
                    }//发送移除成员邮件
                    else if("3".equals(take.getKey()))
                    {
                        String value = take.getValue().toString();
                        log.error(value);
                        String departmentId = value.substring(value.lastIndexOf(',')+1);
                        String userId=value.substring(0,value.lastIndexOf(','));
                        User user = userDao.selectUserByUserId(Integer.parseInt(userId));
                        if (StringUtils.isEmpty(user.getEmail())||"".equals(user.getEmail())){
                            log.error("无邮箱");
                            continue;
                        }
                        String removeEmailContent = EmailConstant.getRemoveEmailContent(Integer.parseInt(departmentId), user.getUserName());
                        sendEmailService.sendWxchangeDutyEmail(user.getEmail(),removeEmailContent,"关于您在部门的成员身份的变更");

                    }
                    else if("4".equals(take.getKey())){
                        String value = take.getValue().toString();
                        log.error(value);
                        String i = value.substring(value.lastIndexOf(',')+1);
                        String applyId=value.substring(0,value.lastIndexOf(','));
                        apply apply = applyDao.selectApplyByApplyId(Integer.parseInt(applyId));
                        if("1".equals(i)){
                            String firstWilling = apply.getFirstWilling();
                            String firstStatus = apply.getFirstStatus();
                        }
                        else if("2".equals(i)){
                            String secondWilling = apply.getSecondWilling();
                            String secondStatus = apply.getSecondStatus();
                        }
                    }

                } catch (InterruptedException e) {

                    log.error("处理apply异常！");
                    throw new RuntimeException(e);
                } catch (Exception e) {
                    log.error("发送邮箱异常！",e);
                    throw new RuntimeException(e);
                }
            }
        }
    }



    @Override
    public boolean insertApply(apply apply) {
        Boolean add = applyDao.insertApply(apply);
        return add;
    }

    @Override
    public apply selectApplybyUserid(Integer userId) {
        apply apply = applyDao.selectApplybyUserid(userId);
        return apply;

    }

    //更新url
    @Override
    public boolean updateApply(apply apply) {
        Boolean update = applyDao.updateApply(apply);
        return update;
    }

    //创建一条apply



    @Override
    public apply selectApplyByApplyId(Integer applyId) {
        return applyDao.selectApplyByApplyId(applyId);
    }

    @Override
    public List<apply> selectApplyByWilling(String department) {
        List<apply> applys = applyDao.selectApplyByWilling(department);
        return applys;

    }


    @Override
    public Integer selectCountByFirstWilling(String department, String startTime, String endTime) {
        Integer integer = applyDao.selectCountByFirstWilling(department,startTime,endTime);
        return integer;
    }

    @Override
    public List<apply> selectApplyBytwoWilling() {
        List<apply> applies = applyDao.selectApplyBytwoWilling();
        return applies;
    }

    @Override
    public apply selectApplyBytimestamp(long timestamp) {
        apply apply = applyDao.selectApplyBytimestamp(timestamp);
        return apply;
    }


    @Override
    public Boolean SetUserId(String userId,String applyId){
        Boolean a = applyDao.SetUserId(userId,applyId);
        return a;
    }

    @Override
    public Boolean reverseWilling(int applyId, String firstStatus, String secondStatus) {
        return applyDao.reverseWilling(applyId,firstStatus,secondStatus);
    }

    @Override
    public void addApply2QueueAndText(Integer applyId) throws InterruptedException {
        Map.Entry<String,Object> queuer=new AbstractMap.SimpleEntry<>("1",applyId);
        applyQueue.put(queuer);
    }

    @Override
    public void addApply2QueueAndPic(String userId) throws InterruptedException {
        Map.Entry<String,Object> queuer=new AbstractMap.SimpleEntry<>("2",userId);
        applyQueue.put(queuer);
    }

    @Override
    public ReturnData getApplyTime() {
        ApplyTime applyTime = applyDao.getApplyTime();
        ReturnData returnData = new ReturnData();
        returnData.setCode(0);
        returnData.setMsg("查询成功");
        returnData.setData(applyTime);
        System.out.println(applyTime.getStartTime());
        System.out.println(applyTime.getEndTime());
        return returnData;
    }

    @Override
    public ReturnData setApplyTime(String startTime, String endTime) {
        ReturnData returnData = new ReturnData();
        if(StringUtils.isEmpty(startTime)||StringUtils.isEmpty(endTime)){
            returnData.setCode(1);
            returnData.setMsg("请设置正确的投递时间段");
            return returnData;
        }

        applyDao.setApplyTime(startTime,endTime);
        returnData.setCode(0);
        returnData.setMsg("设置成功！");
        return returnData;
    }

    @Override
    public void addStatus2QueueToSend(String applyId, int i) throws InterruptedException {
        Map.Entry<String,Object> queuer=new AbstractMap.SimpleEntry<>("4",applyId+','+i);
        applyQueue.put(queuer);
    }

    @Override
    public List<apply> selectApplyByWillingAndTime(String departmentId, String startTime, String endTime) {
        return applyDao.selectApplyByWillingAndTime(departmentId,startTime,endTime);
    }


}



